home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_xemacs.idb / usr / freeware / lib / xemacs-20.4 / lisp / mh-e / mh-utils.el.z / mh-utils.el
Encoding:
Text File  |  1998-05-21  |  34.6 KB  |  978 lines

  1. ;;; mh-utils.el --- mh-e code needed for both sending and reading
  2. ;; Time-stamp: <95/10/22 17:58:16 gildea>
  3.  
  4. ;; Copyright (C) 1993, 1995 Free Software Foundation, Inc.
  5.  
  6. ;; This file is part of mh-e, part of GNU Emacs.
  7.  
  8. ;; GNU Emacs is free software; you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation; either version 2, or (at your option)
  11. ;; any later version.
  12.  
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. ;; GNU General Public License for more details.
  17.  
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with XEmacs; see the file COPYING.  If not, write to the
  20. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  21. ;; Boston, MA 02111-1307, USA.
  22.  
  23. ;;; Synched up with: FSF 19.34.
  24.  
  25. ;;; Commentary:
  26.  
  27. ;; Internal support for mh-e package.
  28.  
  29. ;;; Change Log:
  30.  
  31. ;; $Id: mh-utils.el,v 1.10 1996/06/28 06:56:17 rms Exp $
  32.  
  33. ;;; Code:
  34.  
  35. ;;; Set for local environment:
  36. ;;; mh-progs and mh-lib used to be set in paths.el, which tried to
  37. ;;; figure out at build time which of several possible directories MH
  38. ;;; was installed into.  But if you installed MH after building Emacs,
  39. ;;; this would almost certainly be wrong, so now we do it at run time.
  40.  
  41. (defvar mh-progs nil
  42.   "Directory containing MH commands, such as inc, repl, and rmm.")
  43.  
  44. (defvar mh-lib nil
  45.   "Directory containing the MH library.
  46. This directory contains, among other things,
  47. the mhl program and the components file.")
  48.  
  49. ;;;###autoload
  50. (put 'mh-progs 'risky-local-variable t)
  51. ;;;###autoload
  52. (put 'mh-lib 'risky-local-variable t)
  53.  
  54. ;;; User preferences:
  55.  
  56. (defgroup mh-buffer nil
  57.   "Layout of MH-E buffers"
  58.   :prefix "mh-"
  59.   :group 'mh)
  60.  
  61.  
  62. (defcustom mh-auto-folder-collect t
  63.   "*Whether to start collecting MH folder names immediately in the background.
  64. Non-nil means start a background process collecting the names of all
  65. folders as soon as mh-e is loaded."
  66.   :type 'boolean
  67.   :group 'mh)
  68.  
  69. (defcustom mh-recursive-folders nil
  70.   "*If non-nil, then commands which operate on folders do so recursively."
  71.   :type 'boolean
  72.   :group 'mh)
  73.  
  74. (defcustom mh-clean-message-header nil
  75.   "*Non-nil means clean headers of messages that are displayed or inserted.
  76. The variables `mh-visible-headers' and `mh-invisible-headers' control what
  77. is removed."
  78.   :type 'boolean
  79.   :group 'mh-buffer)
  80.  
  81. (defcustom mh-visible-headers nil
  82.   "*If non-nil, contains a regexp specifying the headers to keep when cleaning.
  83. Only used if `mh-clean-message-header' is non-nil.  Setting this variable
  84. overrides `mh-invisible-headers'."
  85.   :type '(choice (const nil) regexp)
  86.   :group 'mh-buffer)
  87.  
  88. (defvar mh-invisible-headers
  89.   "^Received: \\|^Message-Id: \\|^Remailed-\\|^Via: \\|^Mail-from: \\|^Return-Path: \\|^Delivery-Date: \\|^In-Reply-To: \\|^Resent-"
  90.   "Regexp matching lines in a message header that are not to be shown.
  91. If `mh-visible-headers' is non-nil, it is used instead to specify what
  92. to keep.")
  93.  
  94. (defcustom mh-bury-show-buffer t
  95.   "*Non-nil means that the displayed show buffer for a folder is buried."
  96.   :type 'boolean
  97.   :group 'mh-buffer)
  98.  
  99. (defcustom mh-summary-height 4
  100.   "*Number of lines in MH-Folder window (including the mode line)."
  101.   :type 'integer
  102.   :group 'mh-buffer)
  103.  
  104. (defvar mh-msg-number-regexp "^ *\\([0-9]+\\)"
  105.   "Regexp to find the number of a message in a scan line.
  106. The message's number must be surrounded with \\( \\)")
  107.  
  108. (defvar mh-msg-search-regexp "^[^0-9]*%d[^0-9]"
  109.   "Format string containing a regexp matching the scan listing for a message.
  110. The desired message's number will be an argument to format.")
  111.  
  112. (defcustom mhl-formfile nil
  113.   "*Name of format file to be used by mhl to show and print messages.
  114. A value of T means use the default format file.
  115. Nil means don't use mhl to format messages when showing; mhl is still used,
  116. with the default format file, to format messages when printing them.
  117. The format used should specify a non-zero value for overflowoffset so
  118. the message continues to conform to RFC 822 and mh-e can parse the headers."
  119.   :type '(choice (const nil) (const t) string)
  120.   :group 'mh)
  121. (put 'mhl-formfile 'info-file "mh-e")
  122.  
  123. (defvar mh-default-folder-for-message-function nil
  124.   "Function to select a default folder for refiling or Fcc.
  125. If set to a function, that function is called with no arguments by
  126. `\\[mh-refile-msg]' and `\\[mh-to-fcc]' to get a default when
  127. prompting the user for a folder.  The function is called from within a
  128. save-excursion, with point at the start of the message.  It should
  129. return the folder to offer as the refile or Fcc folder, as a string
  130. with a leading `+' sign.  It can also return an empty string to use no
  131. default, or NIL to calculate the default the usual way.
  132. NOTE: This variable is not an ordinary hook;
  133. It may not be a list of functions.")
  134.  
  135. (defvar mh-find-path-hook nil
  136.   "Invoked by mh-find-path while reading the user's MH profile.")
  137.  
  138. (defvar mh-folder-list-change-hook nil
  139.   "Invoked whenever the cached folder list `mh-folder-list' is changed.")
  140.  
  141. (defvar mh-show-buffer-mode-line-buffer-id "{show-%s} %d"
  142.   "Format string to produce `mode-line-buffer-identification' for show buffers.
  143. First argument is folder name.  Second is message number.")
  144.  
  145. (defvar mh-cmd-note 4
  146.   "Offset to insert notation.")
  147.  
  148. (defvar mh-note-seq "%"
  149.   "String whose first character is used to notate messages in a sequence.")
  150.  
  151. ;;; Internal bookkeeping variables:
  152.  
  153. ;; The value of `mh-folder-list-change-hook' is called whenever
  154. ;; mh-folder-list variable is set.
  155. (defvar mh-folder-list nil)        ;List of folder names for completion.
  156.  
  157. ;; Cached value of the `Path:' component in the user's MH profile.
  158. (defvar mh-user-path nil)        ;User's mail folder directory.
  159.  
  160. ;; An mh-draft-folder of NIL means do not use a draft folder.
  161. ;; Cached value of the `Draft-Folder:' component in the user's MH profile.
  162. (defvar mh-draft-folder nil)        ;Name of folder containing draft messages.
  163.  
  164. ;; Cached value of the `Unseen-Sequence:' component in the user's MH profile.
  165. (defvar mh-unseen-seq nil)        ;Name of the Unseen sequence.
  166.  
  167. ;; Cached value of the `Previous-Sequence:' component in the user's MH profile.
  168. (defvar mh-previous-seq nil)        ;Name of the Previous sequence.
  169.  
  170. ;; Cached value of the `Inbox:' component in the user's MH profile,
  171. ;; or "+inbox" if no such component.
  172. (defvar mh-inbox nil)            ;Name of the Inbox folder.
  173.  
  174. (defconst mh-temp-buffer " *mh-temp*")    ;Name of mh-e scratch buffer.
  175.  
  176. (defvar mh-previous-window-config nil)    ;Window configuration before mh-e command.
  177.  
  178. ;;; Internal variables local to a folder.
  179.  
  180. (defvar mh-current-folder nil)        ;Name of current folder, a string.
  181.  
  182. (defvar mh-show-buffer nil)        ;Buffer that displays message for this folder.
  183.  
  184. (defvar mh-folder-filename nil)        ;Full path of directory for this folder.
  185.   
  186. (defvar mh-msg-count nil)        ;Number of msgs in buffer.
  187.  
  188. (defvar mh-showing nil)            ;If non-nil, show the message in a separate window.
  189.  
  190. ;;; This holds a documentation string used by describe-mode.
  191. (defun mh-showing ()
  192.   "When moving to a new message in the Folder window,
  193. also show it in a separate Show window."
  194.   nil)
  195.  
  196. (defvar mh-seq-list nil)        ;The sequences of this folder.  An alist of (seq . msgs).
  197.  
  198. (defvar mh-seen-list nil)        ;List of displayed messages to be removed from the Unseen sequence.
  199.  
  200. ;; If non-nil, show buffer contains message with all headers.
  201. ;; If nil, show buffer contains message processed normally.
  202. (defvar mh-showing-with-headers nil)    ;Showing message with headers or normally.
  203.  
  204.  
  205. ;;; mh-e macros
  206.  
  207. (defmacro with-mh-folder-updating (save-modification-flag-p &rest body)
  208.   ;; Format is (with-mh-folder-updating (SAVE-MODIFICATION-FLAG-P) &body BODY).
  209.   ;; Execute BODY, which can modify the folder buffer without having to
  210.   ;; worry about file locking or the read-only flag, and return its result.
  211.   ;; If SAVE-MODIFICATION-FLAG-P is non-nil, the buffer's modification
  212.   ;; flag is unchanged, otherwise it is cleared.
  213.   (setq save-modification-flag-p (car save-modification-flag-p)) ; CL style
  214.   (` (prog1
  215.      (let ((mh-folder-updating-mod-flag (buffer-modified-p))
  216.            (buffer-read-only nil)
  217.            (buffer-file-name nil))    ;don't let the buffer get locked
  218.        (prog1
  219.            (progn
  220.          (,@ body))
  221.          (mh-set-folder-modified-p mh-folder-updating-mod-flag)))
  222.        (,@ (if (not save-modification-flag-p)
  223.            '((mh-set-folder-modified-p nil)))))))
  224.  
  225. (put 'with-mh-folder-updating 'lisp-indent-hook 1)
  226.  
  227. (defmacro mh-in-show-buffer (show-buffer &rest body)
  228.   ;; Format is (mh-in-show-buffer (SHOW-BUFFER) &body BODY).
  229.   ;; Display buffer SHOW-BUFFER in other window and execute BODY in it.
  230.   ;; Stronger than save-excursion, weaker than save-window-excursion.
  231.   (setq show-buffer (car show-buffer))    ; CL style
  232.   (` (let ((mh-in-show-buffer-saved-window (selected-window)))
  233.        (switch-to-buffer-other-window (, show-buffer))
  234.        (if mh-bury-show-buffer (bury-buffer (current-buffer)))
  235.        (unwind-protect
  236.        (progn
  237.          (,@ body))
  238.      (select-window mh-in-show-buffer-saved-window)))))
  239.  
  240. (put 'mh-in-show-buffer 'lisp-indent-hook 1)
  241.  
  242. (defmacro mh-make-seq (name msgs) (list 'cons name msgs))
  243.  
  244. (defmacro mh-seq-name (pair) (list 'car pair))
  245.  
  246. (defmacro mh-seq-msgs (pair) (list 'cdr pair))
  247.  
  248.  
  249. ;;; Ensure new buffers won't get this mode if default-major-mode is nil.
  250. (put 'mh-show-mode 'mode-class 'special)
  251.  
  252. (defun mh-show-mode ()
  253.   "Major mode for showing messages in mh-e.
  254. The value of mh-show-mode-hook is called when a new message is displayed."
  255.   (kill-all-local-variables)
  256.   (setq major-mode 'mh-show-mode)
  257.   (mh-set-mode-name "MH-Show")
  258.   (run-hooks 'mh-show-mode-hook))
  259.  
  260.  
  261. (defun mh-maybe-show (&optional msg)
  262.   ;; If in showing mode, then display the message pointed to by the cursor.
  263.   (if mh-showing (mh-show msg)))
  264.  
  265. (defun mh-show (&optional message)
  266.   "Show MESSAGE (default: message at cursor).
  267. Force a two-window display with the folder window on top (size
  268. mh-summary-height) and the show buffer below it.
  269. If the message is already visible, display the start of the message.
  270.  
  271. Display of the message is controlled by setting the variables
  272. `mh-clean-message-header' and `mhl-formfile'.  The default behavior is
  273. to scroll uninteresting headers off the top of the window.
  274. Type \"\\[mh-header-display]\" to see the message with all its headers."
  275.   (interactive)
  276.   (and mh-showing-with-headers
  277.        (or mhl-formfile mh-clean-message-header)
  278.        (mh-invalidate-show-buffer))
  279.   (mh-show-msg message))
  280.  
  281.  
  282. (defun mh-show-msg (msg)
  283.   (if (not msg)
  284.       (setq msg (mh-get-msg-num t)))
  285.   (setq mh-showing t)
  286.   (let ((folder mh-current-folder)
  287.     (clean-message-header mh-clean-message-header)
  288.     (show-window (get-buffer-window mh-show-buffer)))
  289.     (if (not (eql (next-window (minibuffer-window)) (selected-window)))
  290.     (delete-other-windows))        ; force ourself to the top window
  291.     (mh-in-show-buffer (mh-show-buffer)
  292.       (if (and show-window
  293.            (equal (mh-msg-filename msg folder) buffer-file-name))
  294.       (progn            ;just back up to start
  295.         (goto-char (point-min))
  296.         (if (not clean-message-header)
  297.         (mh-start-of-uncleaned-message)))
  298.     (mh-display-msg msg folder))))
  299.   (if (not (= (1+ (window-height)) (screen-height))) ;not horizontally split
  300.       (shrink-window (- (window-height) mh-summary-height)))
  301.   (mh-recenter nil)
  302.   (if (not (memq msg mh-seen-list)) (setq mh-seen-list (cons msg mh-seen-list)))
  303.   (run-hooks 'mh-show-hook))
  304.  
  305.  
  306. (defun mh-display-msg (msg-num folder)
  307.   ;; Display message NUMBER of FOLDER.
  308.   ;; Sets the current buffer to the show buffer.
  309.   (set-buffer folder)
  310.   ;; Bind variables in folder buffer in case they are local
  311.   (let ((formfile mhl-formfile)
  312.     (clean-message-header mh-clean-message-header)
  313.     (invisible-headers mh-invisible-headers)
  314.     (visible-headers mh-visible-headers)
  315.     (msg-filename (mh-msg-filename msg-num))
  316.     (show-buffer mh-show-buffer))
  317.     (if (not (file-exists-p msg-filename))
  318.     (error "Message %d does not exist" msg-num))
  319.     (set-buffer show-buffer)
  320.     (cond ((not (equal msg-filename buffer-file-name))
  321.        (mh-unvisit-file)
  322.        (erase-buffer)
  323.        ;; Changing contents, so this hook needs to be reinitialized.
  324.        ;; pgp.el uses this.
  325.        (if (boundp 'write-contents-hooks) ;Emacs 19
  326.            (kill-local-variable 'write-contents-hooks))
  327.        (if formfile
  328.            (mh-exec-lib-cmd-output "mhl" "-nobell" "-noclear"
  329.                        (if (stringp formfile)
  330.                        (list "-form" formfile))
  331.                        msg-filename)
  332.          (insert-file-contents msg-filename))
  333.        (goto-char (point-min))
  334.        (cond (clean-message-header
  335.           (mh-clean-msg-header (point-min)
  336.                        invisible-headers
  337.                        visible-headers)
  338.           (goto-char (point-min)))
  339.          (t
  340.           (mh-start-of-uncleaned-message)))
  341.        ;; the parts of visiting we want to do (no locking)
  342.        (or (eq buffer-undo-list t)    ;don't save undo info for prev msgs
  343.            (setq buffer-undo-list nil))
  344.        (set-buffer-modified-p nil)
  345.        (set-buffer-auto-saved)
  346.        ;; the parts of set-visited-file-name we want to do (no locking)
  347.        (setq buffer-file-name msg-filename)
  348.        (setq buffer-backed-up nil)
  349.        (auto-save-mode 1)
  350.        (set-mark nil)
  351.        (mh-show-mode)
  352.        (setq mode-line-buffer-identification
  353.          (list (format mh-show-buffer-mode-line-buffer-id
  354.                    folder msg-num)))
  355.        (set-buffer folder)
  356.        (setq mh-showing-with-headers nil)))))
  357.  
  358. (defun mh-start-of-uncleaned-message ()
  359.   ;; position uninteresting headers off the top of the window
  360.   (let ((case-fold-search t))
  361.     (re-search-forward
  362.      "^To:\\|^Cc:\\|^From:\\|^Subject:\\|^Date:" nil t)
  363.     (beginning-of-line)
  364.     (mh-recenter 0)))
  365.  
  366.  
  367. (defun mh-invalidate-show-buffer ()
  368.   ;; Invalidate the show buffer so we must update it to use it.
  369.   (if (get-buffer mh-show-buffer)
  370.       (save-excursion
  371.     (set-buffer mh-show-buffer)
  372.     (mh-unvisit-file))))
  373.  
  374.  
  375. (defun mh-unvisit-file ()
  376.   ;; Separate current buffer from the message file it was visiting.
  377.   (or (not (buffer-modified-p))
  378.       (null buffer-file-name)        ;we've been here before
  379.       (yes-or-no-p (format "Message %s modified; flush changes? "
  380.                (file-name-nondirectory buffer-file-name)))
  381.       (error "Flushing changes not confirmed"))
  382.   (clear-visited-file-modtime)
  383.   (unlock-buffer)
  384.   (setq buffer-file-name nil))
  385.  
  386.   
  387. (defun mh-get-msg-num (error-if-no-message)
  388.   ;; Return the message number of the displayed message.  If the argument
  389.   ;; ERROR-IF-NO-MESSAGE is non-nil, then complain if the cursor is not
  390.   ;; pointing to a message.
  391.   (save-excursion
  392.     (beginning-of-line)
  393.     (cond ((looking-at mh-msg-number-regexp)
  394.        (string-to-int (buffer-substring (match-beginning 1)
  395.                         (match-end 1))))
  396.       (error-if-no-message
  397.        (error "Cursor not pointing to message"))
  398.       (t nil))))
  399.  
  400.  
  401. (defun mh-msg-filename (msg &optional folder)
  402.   ;; Return the file name of MESSAGE in FOLDER (default current folder).
  403.   (expand-file-name (int-to-string msg)
  404.             (if folder
  405.             (mh-expand-file-name folder)
  406.             mh-folder-filename)))
  407.  
  408.  
  409. (defun mh-clean-msg-header (start invisible-headers visible-headers)
  410.   ;; Flush extraneous lines in a message header, from the given POINT to the
  411.   ;; end of the message header.  If VISIBLE-HEADERS is non-nil, it contains a
  412.   ;; regular expression specifying the lines to display, otherwise
  413.   ;; INVISIBLE-HEADERS contains a regular expression specifying lines to
  414.   ;; delete from the header.
  415.   (let ((case-fold-search t))
  416.     (save-restriction
  417.       (goto-char start)
  418.       (if (search-forward "\n\n" nil 'move)
  419.       (backward-char 1))
  420.       (narrow-to-region start (point))
  421.       (goto-char (point-min))
  422.       (if visible-headers
  423.       (while (< (point) (point-max))
  424.         (cond ((looking-at visible-headers)
  425.            (forward-line 1)
  426.            (while (looking-at "[ \t]") (forward-line 1)))
  427.           (t
  428.             (mh-delete-line 1)
  429.             (while (looking-at "[ \t]")
  430.               (mh-delete-line 1)))))
  431.       (while (re-search-forward invisible-headers nil t)
  432.         (beginning-of-line)
  433.         (mh-delete-line 1)
  434.         (while (looking-at "[ \t]")
  435.           (mh-delete-line 1))))
  436.       (unlock-buffer))))
  437.  
  438.  
  439. (defun mh-recenter (arg)
  440.   ;; Like recenter but with two improvements: nil arg means recenter,
  441.   ;; and only does anything if the current buffer is in the selected
  442.   ;; window.  (Commands like save-some-buffers can make this false.)
  443.   (if (eql (get-buffer-window (current-buffer))
  444.        (selected-window))
  445.       (recenter (if arg arg '(t)))))
  446.  
  447.  
  448. (defun mh-delete-line (lines)
  449.   ;; Delete version of kill-line.
  450.   (delete-region (point) (progn (forward-line lines) (point))))
  451.  
  452.  
  453. (defun mh-notate (msg notation offset)
  454.   ;; Marks MESSAGE with the character NOTATION at position OFFSET.
  455.   ;; Null MESSAGE means the message that the cursor points to.
  456.   (save-excursion
  457.     (if (or (null msg)
  458.         (mh-goto-msg msg t t))
  459.     (with-mh-folder-updating (t)
  460.       (beginning-of-line)
  461.       (forward-char offset)
  462.       (delete-char 1)
  463.       (insert notation)))))
  464.  
  465.  
  466. (defun mh-find-msg-get-num (step)
  467.   ;; Return the message number of the message on the current scan line
  468.   ;; or one nearby.  Jumps over non-message lines, such as inc errors.
  469.   ;; STEP tells whether to search forward or backward if we have to search.
  470.   (or (mh-get-msg-num nil)
  471.       (let ((msg-num nil)
  472.         (nreverses 0))
  473.     (while (and (not msg-num)
  474.             (< nreverses 2))
  475.       (cond ((eobp)
  476.          (setq step -1)
  477.          (setq nreverses (1+ nreverses)))
  478.         ((bobp)
  479.          (setq step 1)
  480.          (setq nreverses (1+ nreverses))))
  481.       (forward-line step)
  482.       (setq msg-num (mh-get-msg-num nil)))
  483.     msg-num)))
  484.  
  485. (defun mh-goto-msg (number &optional no-error-if-no-message dont-show)
  486.   "Position the cursor at message NUMBER.
  487. Optional non-nil second argument means return nil instead of
  488. signaling an error if message does not exist; in this case,
  489. the cursor is positioned near where the message would have been.
  490. Non-nil third argument means not to show the message."
  491.   (interactive "NGo to message: ")
  492.   (setq number (prefix-numeric-value number)) ;Emacs 19
  493.   ;; This basic routine tries to be as fast as possible,
  494.   ;; using a binary search and minimal regexps.
  495.   (let ((cur-msg (mh-find-msg-get-num -1))
  496.     (jump-size mh-msg-count))
  497.     (while (and (> jump-size 1)
  498.         cur-msg
  499.         (not (eq cur-msg number)))
  500.       (cond ((< cur-msg number)
  501.          (setq jump-size (min (- number cur-msg)
  502.                   (ash (1+ jump-size) -1)))
  503.          (forward-line jump-size)
  504.          (setq cur-msg (mh-find-msg-get-num 1)))
  505.         (t
  506.          (setq jump-size (min (- cur-msg number)
  507.                   (ash (1+ jump-size) -1)))
  508.          (forward-line (- jump-size))
  509.          (setq cur-msg (mh-find-msg-get-num -1)))))
  510.     (if (eq cur-msg number)
  511.     (progn
  512.       (beginning-of-line)
  513.       (or dont-show
  514.           (mh-maybe-show number)
  515.           t))
  516.       (if (not no-error-if-no-message)
  517.       (error "No message %d" number)))))
  518.  
  519.  
  520. (defun mh-msg-search-pat (n)
  521.   ;; Return a search pattern for message N in the scan listing.
  522.   (format mh-msg-search-regexp n))
  523.  
  524.  
  525. (defun mh-get-profile-field (field)
  526.   ;; Find and return the value of FIELD in the current buffer.
  527.   ;; Returns NIL if the field is not in the buffer.
  528.   (let ((case-fold-search t))
  529.     (goto-char (point-min))
  530.     (cond ((not (re-search-forward (format "^%s" field) nil t)) nil)
  531.       ((looking-at "[\t ]*$") nil)
  532.       (t
  533.        (re-search-forward "[\t ]*\\([^\t \n].*\\)$" nil t)
  534.        (let ((start (match-beginning 1)))
  535.          (end-of-line)
  536.          (buffer-substring start (point)))))))
  537.  
  538. (defvar mail-user-agent 'mh-e-user-agent) ;from reporter.el 3.2
  539.  
  540. (defun mh-find-path ()
  541.   ;; Set mh-progs and mh-lib.
  542.   ;; (This step is necessary if MH was installed after this Emacs was dumped.)
  543.   ;; From profile file, set mh-user-path, mh-draft-folder,
  544.   ;; mh-unseen-seq, mh-previous-seq, mh-inbox.
  545.   (mh-find-progs)
  546.   (save-excursion
  547.     ;; Be sure profile is fully expanded before switching buffers
  548.     (let ((profile (expand-file-name (or (getenv "MH") "~/.mh_profile"))))
  549.       (set-buffer (get-buffer-create mh-temp-buffer))
  550.       (setq buffer-offer-save nil)    ;for people who set default to t
  551.       (erase-buffer)
  552.       (condition-case err
  553.       (insert-file-contents profile)
  554.     (file-error
  555.      (mh-install profile err)))
  556.       (setq mh-user-path (mh-get-profile-field "Path:"))
  557.       (if (not mh-user-path)
  558.       (setq mh-user-path "Mail"))
  559.       (setq mh-user-path
  560.         (file-name-as-directory
  561.          (expand-file-name mh-user-path (expand-file-name "~"))))
  562.       (setq mh-draft-folder (mh-get-profile-field "Draft-Folder:"))
  563.       (if mh-draft-folder
  564.       (progn
  565.         (if (not (mh-folder-name-p mh-draft-folder))
  566.         (setq mh-draft-folder (format "+%s" mh-draft-folder)))
  567.         (if (not (file-exists-p (mh-expand-file-name mh-draft-folder)))
  568.         (error "Draft folder \"%s\" not found.  Create it and try again."
  569.                (mh-expand-file-name mh-draft-folder)))))
  570.       (setq mh-inbox (mh-get-profile-field "Inbox:"))
  571.       (cond ((not mh-inbox)
  572.          (setq mh-inbox "+inbox"))
  573.         ((not (mh-folder-name-p mh-inbox))
  574.          (setq mh-inbox (format "+%s" mh-inbox))))
  575.       (setq mh-unseen-seq (mh-get-profile-field "Unseen-Sequence:"))
  576.       (if mh-unseen-seq
  577.       (setq mh-unseen-seq (intern mh-unseen-seq))
  578.     (setq mh-unseen-seq 'unseen))    ;old MH default?
  579.       (setq mh-previous-seq (mh-get-profile-field "Previous-Sequence:"))
  580.       (if mh-previous-seq
  581.       (setq mh-previous-seq (intern mh-previous-seq)))
  582.       (setq mail-user-agent 'mh-e-user-agent)
  583.       (run-hooks 'mh-find-path-hook))))
  584.  
  585. (defun mh-find-progs ()
  586.   (or (file-exists-p (expand-file-name "inc" mh-progs))
  587.       (setq mh-progs
  588.         (or (mh-path-search exec-path "inc")
  589.         (mh-path-search '("/usr/local/bin/mh/"
  590.                   "/usr/local/mh/"
  591.                   "/usr/bin/mh/" ;Ultrix 4.2
  592.                   "/usr/new/mh/" ;Ultrix <4.2
  593.                   "/usr/contrib/mh/bin/" ;BSDI
  594.                   "/usr/local/bin/"
  595.                   )
  596.                 "inc")
  597.         mh-progs
  598.         "/usr/local/bin/")))
  599.   (or (file-exists-p (expand-file-name "mhl" mh-lib))
  600.       (setq mh-lib
  601.         (or (mh-path-search '("/usr/local/lib/mh/"
  602.                   "/usr/local/mh/lib/"
  603.                   "/usr/local/bin/mh/"
  604.                   "/usr/lib/mh/" ;Ultrix 4.2
  605.                   "/usr/new/lib/mh/" ;Ultrix <4.2
  606.                   "/usr/contrib/mh/lib/" ;BSDI
  607.                   )
  608.                 "mhl")
  609.         (mh-path-search exec-path "mhl") ;unlikely
  610.         mh-lib
  611.         "/usr/local/lib/mh/"))))
  612.  
  613. (defun mh-path-search (path file)
  614.   ;; Search PATH, a list of directory names, for FILE.
  615.   ;; Returns the element of PATH that contains FILE, or nil if not found.
  616.   (while (and path
  617.           (not (file-exists-p (expand-file-name file (car path)))))
  618.     (setq path (cdr path)))
  619.   (car path))
  620.  
  621. (defvar mh-no-install nil)        ;do not run install-mh
  622.  
  623. (defun mh-install (profile error-val)
  624.   ;; Called to do error recovery if we fail to read the profile file.
  625.   ;; If possible, initialize the MH environment.
  626.   (if (or (getenv "MH")
  627.       (file-exists-p profile)
  628.       mh-no-install)
  629.       (signal (car error-val)
  630.           (list (format "Cannot read MH profile \"%s\"" profile)
  631.             (car (cdr (cdr error-val))))))
  632.   ;; The "install-mh" command will output a short note which
  633.   ;; mh-exec-cmd will display to the user.
  634.   ;; The MH 5 version of install-mh might try prompt the user
  635.   ;; for information, which would fail here.
  636.   (mh-exec-cmd (expand-file-name "install-mh" mh-lib) "-auto")
  637.   ;; now try again to read the profile file
  638.   (erase-buffer)
  639.   (condition-case err
  640.       (insert-file-contents profile)
  641.     (file-error
  642.      (signal (car err)            ;re-signal with more specific msg
  643.          (list (format "Cannot read MH profile \"%s\"" profile)
  644.            (car (cdr (cdr err))))))))
  645.  
  646.  
  647. (defun mh-set-folder-modified-p (flag)
  648.   ;; Mark current folder as modified or unmodified according to FLAG.
  649.   (set-buffer-modified-p flag))
  650.  
  651.  
  652. (defun mh-find-seq (name) (assoc name mh-seq-list))
  653.  
  654. (defun mh-seq-to-msgs (seq)
  655.   ;; Return a list of the messages in SEQUENCE.
  656.   (mh-seq-msgs (mh-find-seq seq)))
  657.  
  658.  
  659. (defun mh-add-msgs-to-seq (msgs seq &optional internal-flag)
  660.   ;; Add MESSAGE(s) to the SEQUENCE.  If optional FLAG is non-nil, do not mark
  661.   ;; the message in the scan listing or inform MH of the addition.
  662.   (let ((entry (mh-find-seq seq)))
  663.     (if (and msgs (atom msgs)) (setq msgs (list msgs)))
  664.     (if (null entry)
  665.     (setq mh-seq-list (cons (mh-make-seq seq msgs) mh-seq-list))
  666.     (if msgs (setcdr entry (append msgs (mh-seq-msgs entry)))))
  667.     (cond ((not internal-flag)
  668.        (mh-add-to-sequence seq msgs)
  669.        (mh-notate-seq seq mh-note-seq (1+ mh-cmd-note))))))
  670.  
  671. (autoload 'mh-add-to-sequence "mh-seq")
  672. (autoload 'mh-notate-seq "mh-seq")
  673. (autoload 'mh-read-seq-default "mh-seq")
  674. (autoload 'mh-map-to-seq-msgs "mh-seq")
  675.  
  676.  
  677. (defun mh-set-mode-name (mode-name-string)
  678.   ;; Set the mode-name and ensure that the mode line is updated.
  679.   (setq mode-name mode-name-string)
  680.   ;; Force redisplay of all buffers' mode lines to be considered.
  681.   (save-excursion (set-buffer (other-buffer)))
  682.   (set-buffer-modified-p (buffer-modified-p)))
  683.  
  684.  
  685. (defun mh-prompt-for-folder (prompt default can-create)
  686.   ;; Prompt for a folder name with PROMPT.  Returns the folder's name as a
  687.   ;; string.  DEFAULT is used if the folder exists and the user types return.
  688.   ;; If the CAN-CREATE flag is t, then a non-existent folder is made.
  689.   (if (null default)
  690.       (setq default ""))
  691.   (let* ((prompt (format "%s folder%s" prompt
  692.              (if (equal "" default)
  693.                  "? "
  694.                  (format " [%s]? " default))))
  695.      read-name folder-name)
  696.     (if (null mh-folder-list)
  697.     (mh-set-folder-list))
  698.     (while (and (setq read-name (completing-read prompt mh-folder-list
  699.                         nil nil "+"))
  700.         (equal read-name "")
  701.         (equal default "")))
  702.     (cond ((or (equal read-name "") (equal read-name "+"))
  703.        (setq read-name default))
  704.       ((not (mh-folder-name-p read-name))
  705.        (setq read-name (format "+%s" read-name))))
  706.     (setq folder-name read-name)
  707.     (cond ((and (> (length folder-name) 0)
  708.         (eql (aref folder-name (1- (length folder-name))) ?/))
  709.        (setq folder-name (substring folder-name 0 -1))))
  710.     (let ((new-file-p (not (file-exists-p (mh-expand-file-name folder-name)))))
  711.       (cond ((and new-file-p
  712.           (y-or-n-p
  713.            (format "Folder %s does not exist.  Create it? " folder-name)))
  714.          (message "Creating %s" folder-name)
  715.          (call-process "mkdir" nil nil nil (mh-expand-file-name folder-name))
  716.          (message "Creating %s...done" folder-name)
  717.          (setq mh-folder-list (cons (list read-name) mh-folder-list))
  718.          (run-hooks 'mh-folder-list-change-hook))
  719.         (new-file-p
  720.          (error "Folder %s is not created" folder-name))
  721.         ((not (file-directory-p (mh-expand-file-name folder-name)))
  722.          (error "\"%s\" is not a directory"
  723.             (mh-expand-file-name folder-name)))
  724.         ((and (null (assoc read-name mh-folder-list))
  725.           (null (assoc (concat read-name "/") mh-folder-list)))
  726.          (setq mh-folder-list (cons (list read-name) mh-folder-list))
  727.          (run-hooks 'mh-folder-list-change-hook))))
  728.     folder-name))
  729.  
  730.  
  731. (defvar mh-make-folder-list-process nil) ;The background process collecting the folder list.
  732.  
  733. (defvar mh-folder-list-temp nil)    ;mh-folder-list as it is being built.
  734.  
  735. (defvar mh-folder-list-partial-line "")    ;Start of last incomplete line from folder process.
  736.  
  737. (defun mh-set-folder-list ()
  738.   ;; Sets mh-folder-list correctly.
  739.   ;; A useful function for the command line or for when you need to
  740.   ;; sync by hand.  Format is in a form suitable for completing read.
  741.   (message "Collecting folder names...")
  742.   (if (not mh-make-folder-list-process)
  743.       (mh-make-folder-list-background))
  744.   (while (eq (process-status mh-make-folder-list-process) 'run)
  745.     (accept-process-output mh-make-folder-list-process))
  746.   (setq mh-folder-list mh-folder-list-temp)
  747.   (run-hooks 'mh-folder-list-change-hook)
  748.   (setq mh-folder-list-temp nil)
  749.   (delete-process mh-make-folder-list-process)
  750.   (setq mh-make-folder-list-process nil)
  751.   (message "Collecting folder names...done"))
  752.  
  753. (defun mh-make-folder-list-background ()
  754.   ;; Start a background process to compute a list of the user's folders.
  755.   ;; Call mh-set-folder-list to wait for the result.
  756.   (cond
  757.    ((not mh-make-folder-list-process)
  758.     (mh-find-path)
  759.     (let ((process-connection-type nil))
  760.       (setq mh-make-folder-list-process
  761.         (start-process "folders" nil (expand-file-name "folders" mh-progs)
  762.                "-fast"
  763.                (if mh-recursive-folders
  764.                    "-recurse"
  765.                  "-norecurse")))
  766.       (set-process-filter mh-make-folder-list-process
  767.               'mh-make-folder-list-filter)
  768.       (process-kill-without-query mh-make-folder-list-process)))))
  769.  
  770. (defun mh-make-folder-list-filter (process output)
  771.   ;; parse output from "folders -fast"
  772.   (let ((position 0)
  773.     line-end
  774.     new-folder
  775.     (prevailing-match-data (match-data)))
  776.     (unwind-protect
  777.     ;; make sure got complete line
  778.     (while (setq line-end (string-match "\n" output position))
  779.       (setq new-folder (format "+%s%s"
  780.                    mh-folder-list-partial-line
  781.                    (substring output position line-end)))
  782.       (setq mh-folder-list-partial-line "")
  783.       ;; is new folder a subfolder of previous?
  784.       (if (and mh-folder-list-temp
  785.            (string-match
  786.             (regexp-quote
  787.              (concat (car (car mh-folder-list-temp)) "/"))
  788.             new-folder))
  789.           ;; append slash to parent folder for better completion
  790.           ;; (undone by mh-prompt-for-folder)
  791.           (setq mh-folder-list-temp
  792.             (cons
  793.              (list new-folder)
  794.              (cons
  795.               (list (concat (car (car mh-folder-list-temp)) "/"))
  796.               (cdr mh-folder-list-temp))))
  797.         (setq mh-folder-list-temp
  798.           (cons (list new-folder)
  799.             mh-folder-list-temp)))
  800.       (setq position (1+ line-end)))
  801.       (store-match-data prevailing-match-data))
  802.     (setq mh-folder-list-partial-line (substring output position))))
  803.  
  804.  
  805. (defun mh-folder-name-p (name)
  806.   ;; Return non-NIL if NAME is possibly the name of a folder.
  807.   ;; A name (a string or symbol) can be a folder name if it begins with "+".
  808.   (if (symbolp name)
  809.       (eql (aref (symbol-name name) 0) ?+)
  810.     (and (> (length name) 0)
  811.      (eql (aref name 0) ?+))))
  812.  
  813.  
  814. ;;; Issue commands to MH.
  815.  
  816.  
  817. (defun mh-exec-cmd (command &rest args)
  818.   ;; Execute mh-command COMMAND with ARGS.
  819.   ;; The side effects are what is desired.
  820.   ;; Any output is assumed to be an error and is shown to the user.
  821.   ;; The output is not read or parsed by mh-e.
  822.   (save-excursion
  823.     (set-buffer (get-buffer-create mh-temp-buffer))
  824.     (erase-buffer)
  825.     (apply 'call-process
  826.        (expand-file-name command mh-progs) nil t nil
  827.        (mh-list-to-string args))
  828.     (if (> (buffer-size) 0)
  829.     (save-window-excursion
  830.       (switch-to-buffer-other-window mh-temp-buffer)
  831.       (sit-for 5)))))
  832.  
  833.  
  834. (defun mh-exec-cmd-error (env command &rest args)
  835.   ;; In environment ENV, execute mh-command COMMAND with args ARGS.
  836.   ;; ENV is nil or a string of space-separated "var=value" elements.
  837.   ;; Signals an error if process does not complete successfully.
  838.   (save-excursion
  839.     (set-buffer (get-buffer-create mh-temp-buffer))
  840.     (erase-buffer)
  841.     (let ((status
  842.        (if env
  843.            ;; the shell hacks necessary here shows just how broken Unix is
  844.            (apply 'call-process "/bin/sh" nil t nil "-c"
  845.               (format "%s %s ${1+\"$@\"}"
  846.                   env 
  847.                   (expand-file-name command mh-progs))
  848.               command
  849.               (mh-list-to-string args))
  850.            (apply 'call-process
  851.               (expand-file-name command mh-progs) nil t nil
  852.               (mh-list-to-string args)))))
  853.       (mh-handle-process-error command status))))
  854.  
  855.  
  856. (defun mh-exec-cmd-daemon (command &rest args)
  857.   ;; Execute MH command COMMAND with ARGS in the background.
  858.   ;; Any output from command is displayed in an asynchronous pop-up window.
  859.   (save-excursion
  860.     (set-buffer (get-buffer-create mh-temp-buffer))
  861.     (erase-buffer))
  862.   (let* ((process-connection-type nil)
  863.      (process (apply 'start-process
  864.              command nil
  865.              (expand-file-name command mh-progs)
  866.              (mh-list-to-string args))))
  867.     (set-process-filter process 'mh-process-daemon)))
  868.  
  869. (defun mh-process-daemon (process output)
  870.   ;; Process daemon that puts output into a temporary buffer.
  871.   (set-buffer (get-buffer-create mh-temp-buffer))
  872.   (insert-before-markers output)
  873.   (display-buffer mh-temp-buffer))
  874.  
  875.  
  876. (defun mh-exec-cmd-quiet (raise-error command &rest args)
  877.   ;; Args are RAISE-ERROR, COMMANDS, ARGS....
  878.   ;; Execute MH command COMMAND with ARGS.  ARGS is a list of strings.
  879.   ;; Return at start of mh-temp buffer, where output can be parsed and used.
  880.   ;; Returns value of call-process, which is 0 for success,
  881.   ;; unless RAISE-ERROR is non-nil, in which case an error is signaled
  882.   ;; if call-process returns non-0.
  883.   (set-buffer (get-buffer-create mh-temp-buffer))
  884.   (erase-buffer)
  885.   (let ((value
  886.      (apply 'call-process
  887.         (expand-file-name command mh-progs) nil t nil
  888.         args)))
  889.     (goto-char (point-min))
  890.     (if raise-error
  891.     (mh-handle-process-error command value)
  892.       value)))
  893.  
  894.  
  895. (defun mh-exec-cmd-output (command display &rest args)
  896.   ;; Execute MH command COMMAND with DISPLAY flag and ARGS.
  897.   ;; Put the output into buffer after point.  Set mark after inserted text.
  898.   ;; Output is expected to be shown to user, not parsed by mh-e.
  899.   (push-mark (point) t)
  900.   (apply 'call-process
  901.      (expand-file-name command mh-progs) nil t display
  902.      (mh-list-to-string args))
  903.   (exchange-point-and-mark))
  904.  
  905.  
  906. (defun mh-exec-lib-cmd-output (command &rest args)
  907.   ;; Execute MH library command COMMAND with ARGS.
  908.   ;; Put the output into buffer after point.  Set mark after inserted text.
  909.   (apply 'mh-exec-cmd-output (expand-file-name command mh-lib) nil args))
  910.  
  911.  
  912. (defun mh-handle-process-error (command status)
  913.   ;; Raise error if COMMAND returned non-0 STATUS, otherwise return STATUS.
  914.   ;; STATUS is return value from call-process.
  915.   ;; Program output is in current buffer.
  916.   ;; If output is too long to include in error message, display the buffer.
  917.   (cond ((eql status 0)            ;success
  918.      status)
  919.     ((stringp status)        ;kill string
  920.      (error "%s: %s" command status))
  921.     (t                ;exit code
  922.      (cond
  923.       ((= (buffer-size) 0)        ;program produced no error message
  924.        (error "%s: exit code %d" command status))
  925.       (t
  926.        ;; will error message fit on one line?
  927.        (goto-line 2)
  928.        (if (and (< (buffer-size) (screen-width))
  929.             (eobp))
  930.            (error "%s"
  931.               (buffer-substring 1 (progn (goto-char 1)
  932.                          (end-of-line)
  933.                          (point))))
  934.          (display-buffer (current-buffer))
  935.          (error "%s failed with status %d.  See error message in other window."
  936.             command status)))))))
  937.  
  938.  
  939. (defun mh-expand-file-name (filename &optional default)
  940.   ;; Just like `expand-file-name', but also handles MH folder names.
  941.   ;; Assumes that any filename that starts with '+' is a folder name.
  942.    (if (mh-folder-name-p filename)
  943.        (expand-file-name (substring filename 1) mh-user-path)
  944.      (expand-file-name filename default)))
  945.  
  946.  
  947. (defun mh-list-to-string (l)
  948.   ;; Flattens the list L and makes every element of the new list into a string.
  949.   (nreverse (mh-list-to-string-1 l)))
  950.  
  951. (defun mh-list-to-string-1 (l)
  952.   (let ((new-list nil))
  953.     (while l
  954.       (cond ((null (car l)))
  955.         ((symbolp (car l))
  956.          (setq new-list (cons (symbol-name (car l)) new-list)))
  957.         ((numberp (car l))
  958.          (setq new-list (cons (int-to-string (car l)) new-list)))
  959.         ((equal (car l) ""))
  960.         ((stringp (car l)) (setq new-list (cons (car l) new-list)))
  961.         ((listp (car l))
  962.          (setq new-list (nconc (mh-list-to-string-1 (car l))
  963.                    new-list)))
  964.         (t (error "Bad element in mh-list-to-string: %s" (car l))))
  965.       (setq l (cdr l)))
  966.     new-list))
  967.  
  968. (provide 'mh-utils)
  969.  
  970. (and (not noninteractive)
  971.      mh-auto-folder-collect
  972.      (let ((mh-no-install t))        ;only get folders if MH installed
  973.        (condition-case err
  974.        (mh-make-folder-list-background)
  975.      (file-error))))        ;so don't complain if not installed
  976.  
  977. ;;; mh-utils.el ends here
  978.